package cn.czh.system.service.impl;


import cn.czh.system.domain.Menu;
import cn.czh.system.domain.Role;
import cn.czh.system.mapper.MenuMapper;
import cn.czh.system.mapper.RoleMapper;
import cn.czh.system.service.IRoleService;
import cn.czh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addRoleMenuAndPermission(role);
    }

    @Override
    @Transactional
    public void del(Long id) {
        //删除角色菜单中间表
        roleMapper.delMenuByRoleId(id);
        //删除角色权限中间表
        roleMapper.delPermissionByRoleId(id);
        //删除员工角色中间表
        roleMapper.delEmployeeByRoleId(id);
        super.del(id);
    }

    @Override
    public void patchDel(List<Long> ids) {
        for (Long id : ids) {
            del(id);
        }
    }

    @Override
    @Transactional
    public void update(Role role) {
        super.update(role);
        //先删除旧的菜单和权限
        //删除角色菜单中间表
        roleMapper.delMenuByRoleId(role.getId());
        //删除权限菜单中间表
        roleMapper.delPermissionByRoleId(role.getId());
        addRoleMenuAndPermission(role);
    }

    public void addRoleMenuAndPermission(Role role){
        List<Long> menus = role.getMenus();
        if (menus.size()>0){ //当前角色选择了菜单
            roleMapper.addRoleMenu(role);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size()>0){ //当前权限选择了菜单
            roleMapper.addRolePermission(role);

        }
    }

    @Override
    public List<Long> findPermissionByRoleId(Long id) {

        return roleMapper.findPermissionByRoleId(id);
    }



    @Override
    public List<Long[]> findMenuByRoleId(Long id) {
        //获取所有的菜单对象
        List<Long> menuId = roleMapper.findMenuIdByRoleId(id);
        //创建一个数组来返回给前端的menus
        List<Long[]> list = new ArrayList<>();
        //遍历所有菜单
        for (Long longs : menuId){
            //根据id查询菜单
            Menu menu = menuMapper.loadById(longs);
            //创建一个新数组
            Long[] L = new Long[2];
            //索引为0位置的是父级菜单
            L[0] = menu.getParent_id();
            //索引为1位置的是子级菜单
            L[1] = longs;
            //添加到list数组
            list.add(L);
        }
        //返回给前端
        return list;
    }


}
